﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace QuanLyPhongKham
{
    public partial class frmNhapkho : BaseUserControl
    {
        private DAL.AccessData m;
        private string sql = "", s_mmyy = "", user = "", s_ngay = "", s_vat, s_tyle;
        private bool bNew, bEdit, bSave = false;
        private int i_userid, i_mabd, i_vat,manguon_old=0,makho_old=0;
        private long l_id = 0;
        private decimal d_soluong, d_soluongcu, d_dongia, d_giaban, d_giamua, d_giabancu, d_giamuacu, d_sotien_vat, d_vat_sotien, d_st_vat, d_sl1, d_sl2, d_tyle;
        private DataTable dtdmbd = new DataTable();
        private DataTable dtnx = new DataTable();
        private DataTable dtct = new DataTable();
        private DataTable dtll = new DataTable();
        private DataTable dtthem = new DataTable();
        private DataTable dtxoa = new DataTable();
        private DataTable dtsave = new DataTable();

        public frmNhapkho(DAL.AccessData acc, string mmyy, int userid, string ngay)
        {
            this.m = acc;
            this.s_mmyy = mmyy;
            this.i_userid = userid;
            InitializeComponent();
        }
        private void frmNhapkho_Load(object sender, EventArgs e)
        {
            user=m.user;
            nguon.DisplayMember = "TEN";
            nguon.ValueMember = "ID";
            nguon.DataSource = m.get_data("select id,ten from "+user+".d_dmnguon order by id").Tables[0];
            kho.DisplayMember = "TEN";
            kho.ValueMember = "ID";
            kho.DataSource = m.get_data("select id,ten from "+user+".d_dmkho order by id").Tables[0];
            cboSophieu.DisplayMember = "SOPHIEU";
            cboSophieu.ValueMember = "ID";
            listDmnx.DisplayMember = "ID";
            listDmnx.ValueMember="TEN";
            dtnx = m.get_data("select * from " + user + ".d_dmnx order by id").Tables[0];
            listDmnx.DataSource = dtnx;
            load_sophieu();
            listDmbd.DisplayMember = "MA";
            listDmbd.ValueMember = "TEN";
            if (dtll.Rows.Count > 0)
            {
                l_id = long.Parse(cboSophieu.SelectedValue.ToString());
            }
            else l_id = 0;
            if (l_id == 0)
            {
                load_head();
                load_grid();
            }
            AddGridTableStyle();
            ena_object(false);
            ena_button(false);
            ref_text();
            cboSophieu.Focus();
        }
        private void load_sophieu()
        {
            sql = "select * from " + user + ".d_nhapll_" + s_mmyy + " where loai='M' and userid=" + i_userid;
            dtll = m.get_data(sql).Tables[0];
            cboSophieu.DataSource = dtll;
        }
        private void load_head()
        {
            DataRow r = m.getrowbyid(dtll, "id=" + l_id);
            if (r != null)
            {
                sophieu.Text = r["sophieu"].ToString();
                ngaysp.Text = r["ngaysp"].ToString();
                hoadon.Text = r["sohd"].ToString();
                ngayhd.Text = r["ngayhd"].ToString();
                nguoigiao.Text = r["nguoigiao"].ToString();
                mancc.Text = r["madv"].ToString();
                tennhacc.Text = m.getrowbyid(dtnx, "id=" + int.Parse(r["madv"].ToString()))["ten"].ToString();
                nguon.SelectedValue = r["manguon"].ToString();
                kho.SelectedValue = r["makho"].ToString();
                tkno.Text = r["no"].ToString();
                tkco.Text = r["co"].ToString();
                chietkhau.Text = r["chietkhau"].ToString();
            }
        }
        private void load_grid()
        {
            sql = "select a.stt,a.mabd,a.madv,b.ma,trim(b.ten)||' '||b.hamluong as ten,nullif(b.tenhc,' ') as tenhc,b.dang,a.handung,a.losx,";
            sql+= "a.soluong,a.dongia,a.vat,a.sotien,round(a.soluong*a.giamua,3) as tongtien,a.giaban,a.giamua,c.ten as tenhang,d.ten as tennuoc,a.sl1,a.sl2,a.tyle,";
            sql+= "a.giabancu,a.giamuacu,a.tyle_ggia,a.st_ggia,case when a.vat=0 then 0 else round(a.sotien/a.vat,3) end as sotienvat ";
            sql+= " from " + user + ".d_nhapct_"+s_mmyy+" a," + user + ".d_dmbd b," + user + ".d_dmhang c," + user + ".d_dmnuoc d where a.mabd=b.id and b.mahang=c.id and b.manuoc=d.id and a.id=" + l_id + " order by a.stt";
            dtct = m.get_data(sql).Tables[0];
            dataGrid1.DataSource = dtct;
            dtthem = dtct.Clone();
            dtxoa = dtct.Clone();
        }
        private void AddGridTableStyle()
        {
            DataGridColoredTextBoxColumn TextCol;
            delegateGetColorRowCol de = new delegateGetColorRowCol(MyGetColorRowCol);
            DataGridTableStyle ts = new DataGridTableStyle();
            ts.MappingName = dtct.TableName;
            ts.AlternatingBackColor = Color.Linen;
            ts.BackColor = Color.GhostWhite;
            ts.ForeColor = Color.MidnightBlue;
            ts.GridLineColor = SystemColors.Control;
            ts.HeaderBackColor = SystemColors.Control;
            ts.HeaderForeColor = Color.Navy;
            ts.SelectionBackColor = Color.Teal;
            ts.SelectionForeColor = Color.White;
            ts.RowHeaderWidth = 5;
            ts.AllowSorting = false;

            TextCol = new DataGridColoredTextBoxColumn(de, 0);
            TextCol.MappingName = "stt";
            TextCol.HeaderText = "Stt";
            TextCol.Width = 30;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 0);
            TextCol.MappingName = "ma";
            TextCol.HeaderText = "Mã số";
            TextCol.Width = 50;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 0);
            TextCol.MappingName = "ten";
            TextCol.HeaderText = "Tên thuốc - hàm lượng";
            TextCol.Width = 230;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 0);
            TextCol.MappingName = "tenhc";
            TextCol.HeaderText = "Hoạt chất";
            TextCol.Width = 150;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 0);
            TextCol.MappingName = "dang";
            TextCol.HeaderText = "ĐVT";
            TextCol.Width = 50;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 0);
            TextCol.MappingName = "handung";
            TextCol.HeaderText = "Date";
            TextCol.Width = 30;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 0);
            TextCol.MappingName = "losx";
            TextCol.HeaderText = "Lô SX";
            TextCol.Width = 50;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 0);
            TextCol.MappingName = "soluong";
            TextCol.HeaderText = "Số lượng";
            TextCol.Width = 60;
            TextCol.Format = "###,###,###,##0.0";
            TextCol.Alignment = HorizontalAlignment.Right;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 0);
            TextCol.MappingName = "dongia";
            TextCol.HeaderText = "Đơn giá";
            TextCol.Width = 100;
            TextCol.Format = "###,###,###,##0.00"; 
            TextCol.Alignment = HorizontalAlignment.Right;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 0);
            TextCol.MappingName = "sotien";
            TextCol.HeaderText = "Số tiền";
            TextCol.Width = 100;
            TextCol.Format = "###,###,###,##0.00"; 
            TextCol.Alignment = HorizontalAlignment.Right;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 0);
            TextCol.MappingName = "vat";
            TextCol.HeaderText = "Thuế(%)";
            TextCol.Width = 60;
            TextCol.Format = "##0";
            TextCol.Alignment = HorizontalAlignment.Right;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 0);
            TextCol.MappingName = "sotienvat";
            TextCol.HeaderText = "Tiền thuế";
            TextCol.Width = 100;
            TextCol.Format = "###,###,###,##0.00";
            TextCol.Alignment = HorizontalAlignment.Right;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 0);
            TextCol.MappingName = "tongtien";
            TextCol.HeaderText = "Tổng tiền";
            TextCol.Width = 100;
            TextCol.Format = "###,###,###,##0.00"; 
            TextCol.Alignment = HorizontalAlignment.Right;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 0);
            TextCol.MappingName = "giaban";
            TextCol.HeaderText = "Giá bán";
            TextCol.Width = 100;
            TextCol.Format = "###,###,###,##0.00";
            TextCol.Alignment = HorizontalAlignment.Right;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 0);
            TextCol.MappingName = "tenhang";
            TextCol.HeaderText = "Hãng";
            TextCol.Width = 150;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 0);
            TextCol.MappingName = "tennuoc";
            TextCol.HeaderText = "Nước";
            TextCol.Width = 150;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);
        }
        public Color MyGetColorRowCol(int row, int col)
        {
            Color c = Color.Navy;
            try
            {
                if (row == dataGrid1.CurrentRowIndex)
                {
                    dataGrid1.Select(row);
                    c = Color.White;
                }
            }
            catch
            {
            }
            return c;
        }
        public delegate Color delegateGetColorRowCol(int row, int col);
        public class DataGridColoredTextBoxColumn : DataGridTextBoxColumn
        {
            private delegateGetColorRowCol _getColorRowCol;
            private int _column;
            public DataGridColoredTextBoxColumn(delegateGetColorRowCol getcolorRowCol, int column)
            {
                _getColorRowCol = getcolorRowCol;
                _column = column;
            }
            protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush foreBrush, bool alignToRight)
            {
                try
                {
                    foreBrush = new SolidBrush(_getColorRowCol(rowNum, this._column));
                }

                catch { }
                finally
                {
                    base.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight);
                }
            }
        }
        private void load_dm()
        {
            sql = "select a.ma,trim(a.ten)||' '||a.hamluong as ten,trim(b.ten)||'/'||c.ten as hang,trim(a.dang)||'/'||trim(a.donvi) as dang,a.tenhc,a.id,a.giaban,a.dongia,b.ten as tenhang,c.ten as tennuoc,a.manhom";//,nullif(d.ma,' ') as sotk ;
            sql+=" from " + user + ".d_dmbd a inner join " + user + ".d_dmhang b on a.mahang=b.id inner join " + user + ".d_dmnuoc c on a.manuoc=c.id where a.hide=0";
            sql+= " order by a.ten";
            dtdmbd = m.get_data(sql).Tables[0];
            listDmbd.DataSource = dtdmbd;
        }
        private void sophieu_Validated(object sender, System.EventArgs e)
        {
            if (l_id != 0) return;
            try
            {
                DataRow r = m.getrowbyid(dtll, "sophieu='" + sophieu.Text + "'");
                if (r != null)
                {
                    MessageBox.Show("Số phiếu đã nhập !", DAL.AccessData.Msg);
                    sophieu.Focus();
                }
            }
            catch { }
        }
        private void ena_object(bool ena)
        {
            sophieu.Visible = ena;
            cboSophieu.Visible = !ena;
            cboSophieu.BringToFront();
            sophieu.BringToFront();
            ngaysp.Enabled = ena;
            hoadon.Enabled = ena;
            ngayhd.Enabled = ena;
            mancc.Enabled = ena;
            tennhacc.Enabled = ena;
            nguoigiao.Enabled = ena;
            nguon.Enabled = ena;
            kho.Enabled = ena;
            tkno.Enabled = ena;
            tkco.Enabled = tkno.Enabled;
            mathuoc.Enabled = ena;
            tenthuoc.Enabled = ena;
            sl1.Enabled = ena;
            sl2.Enabled = ena;
            handung.Enabled = ena;
            losx.Enabled = ena;
            giamua.Enabled = ena;
            sotien_vat.Enabled = ena;
            giamua.Enabled = ena;
            giaban.Enabled = ena;
            tyle.Enabled = giaban.Enabled;
            vat.Enabled = ena;
        }
        private void ena_button(bool ena)
        {
            butMoi.Enabled = !ena;
            butSua.Enabled = !ena;
            butThem.Enabled = ena;
            butXoa.Enabled = ena;
            butLuu.Enabled = ena;
            butBoqua.Enabled = ena;
            butHuy.Enabled = !ena;
            butIn.Enabled = !ena;
            butKetthuc.Enabled = !ena;
        }
        private void emp_head()
        {
            l_id = 0;
            sophieu.Text = "";
            ngaysp.Text = s_ngay;
            hoadon.Text = "";
            ngayhd.Text = s_ngay;
            mancc.Text = "";
            tennhacc.Text = "";
            nguoigiao.Text = "";
            kho.SelectedIndex = 0;
            if(nguon.Items.Count>0) nguon.SelectedIndex = 0;
            tkno.Text = "";
            tkco.Text = "";
            chietkhau.Text = "0";
        }
        private void emp_detail()
        {
            d_dongia = 0; d_giaban = 0; d_giabancu = 0; d_giamua = 0; d_giamuacu = 0; d_sl1 = 0; d_sl2 = 0; d_soluong = 0;
            d_soluongcu = 0; d_sotien_vat = 0; d_st_vat = 0; d_tyle = 0; d_vat_sotien = 0;
            mathuoc.Text = ""; tenthuoc.Text = ""; hoatchat.Text = ""; dvt.Text = "";
            soluong.Text = ""; sl1.Text = ""; sl2.Text = "1"; giamua.Text = d_giamua.ToString("###,###,##0.00");
            sotien_vat.Text = d_sotien_vat.ToString("###,###,##0.00"); vat.Text = i_vat.ToString(); vat_sotien.Text = d_vat_sotien.ToString("###,###,##0.00"); st_vat.Text = d_st_vat.ToString("###,###,##0.00");
            handung.Text = ""; losx.Text = "";
            giaban.Text = d_giaban.ToString("###,###,##0.00"); tyle.Text = d_tyle.ToString("###,###,##0.00");
            hang.Text = ""; nuocsx.Text = ""; 
        }
        private void ref_text()
        {
            try
            {
                int i = dataGrid1.CurrentCell.RowNumber;
                stt.Text = dataGrid1[i, 0].ToString();
                DataRow r1 = m.getrowbyid(dtct, "stt=" + int.Parse(stt.Text));
                if (r1 != null)
                {
                    mathuoc.Text = r1["ma"].ToString();
                    tenthuoc.Text = r1["ten"].ToString();
                    hoatchat.Text = r1["tenhc"].ToString();
                    dvt.Text = r1["dang"].ToString();
                    handung.Text = r1["handung"].ToString();
                    losx.Text = r1["losx"].ToString();
                    hang.Text = r1["tenhang"].ToString();
                    nuocsx.Text = r1["tennuoc"].ToString();
                    d_soluong = (r1["soluong"].ToString() != "") ? decimal.Parse(r1["soluong"].ToString()) : 0;
                    d_dongia = (r1["dongia"].ToString() != "") ? decimal.Parse(r1["dongia"].ToString()) : 0;
                    d_sotien_vat = (r1["sotien"].ToString() != "") ? decimal.Parse(r1["sotien"].ToString()) : 0;
                    d_vat_sotien = (r1["tongtien"].ToString() != "") ? decimal.Parse(r1["tongtien"].ToString()) : 0;
                    i_vat = (r1["vat"].ToString() != "") ? int.Parse(r1["vat"].ToString()) : 0;
                    d_st_vat = (r1["sotienvat"].ToString() != "") ? decimal.Parse(r1["sotienvat"].ToString()) : 0;
                    d_giaban = (r1["giaban"].ToString() != "") ? decimal.Parse(r1["giaban"].ToString()) : 0;
                    d_sl1 = (r1["sl1"].ToString() != "") ? decimal.Parse(r1["sl1"].ToString()) : 0;
                    d_sl2 = (r1["sl2"].ToString() != "") ? decimal.Parse(r1["sl2"].ToString()) : 0;
                    d_tyle = (r1["tyle"].ToString() != "") ? decimal.Parse(r1["tyle"].ToString()) : 0;
                    sl1.Text = d_sl1.ToString("###,###,##0");
                    sl2.Text = d_sl2.ToString("###,###,##0");
                    tyle.Text = d_tyle.ToString("#,##0.00");
                    soluong.Text = d_soluong.ToString("###,###,##0.0");
                    giamua.Text = d_dongia.ToString("###,###,##0.00");
                    sotien_vat.Text = d_sotien_vat.ToString("###,###,##0.00");
                    vat_sotien.Text = d_vat_sotien.ToString("###,###,##0.00");
                    vat.Text = i_vat.ToString("##0");
                    st_vat.Text = d_st_vat.ToString("###,###,##0.00");
                    giaban.Text = d_giaban.ToString("###,###,##0.00");
                    d_giabancu = (r1["giabancu"].ToString() != "") ? decimal.Parse(r1["giabancu"].ToString()) : 0;
                    giaban_cu.Text = d_giabancu.ToString("###,###,##0.00");
                    d_giamuacu = (r1["giamuacu"].ToString() != "") ? decimal.Parse(r1["giamuacu"].ToString()) : 0;
                    giamua_cu.Text = d_giamuacu.ToString("###,###,##0.00");
                    d_soluongcu = d_soluong;
                }
            }
            catch { emp_detail(); }
        }
        private void butMoi_Click(object sender, EventArgs e)
        {
            if (m.bKhoaso(s_mmyy))
            {
                MessageBox.Show("Số liệu tháng" + s_mmyy.Substring(0, 2) + " năm " + s_mmyy.Substring(2, 2) + "đã khóa !\nNếu cần thay đổi thì vào mục khai báo hệ thống!", DAL.AccessData.Msg);
                return;
            }
            if (dtdmbd.Rows.Count == 0) load_dm();
            ena_object(true);
            ena_button(true);
            emp_head();
            emp_detail();
            dtct.Clear();
            dtxoa.Clear(); dtthem.Clear();
            manguon_old = 0; makho_old = 0;
            bNew = true; bEdit = false; 
            sophieu.Focus();
        }
        private void butThem_Click(object sender, EventArgs e)
        {
            if (kiemtra())
            {
                if (bEdit)
                {
                    m.updrec_nhapct(dtthem, m.get_stt(dtthem), i_mabd, mathuoc.Text, tenthuoc.Text, hoatchat.Text, dvt.Text, handung.Text, losx.Text, int.Parse(mancc.Text), d_soluong, d_dongia, d_sotien_vat, int.Parse(vat.Text), d_sotien_vat, d_giaban, d_giamua, d_sl1, d_sl2, d_tyle, d_giabancu, d_giamuacu, d_vat_sotien); 
                }
                m.updrec_nhapct(dtct, m.get_stt(dtct), i_mabd, mathuoc.Text, tenthuoc.Text, hoatchat.Text, dvt.Text, handung.Text, losx.Text, int.Parse(mancc.Text), d_soluong, d_dongia, d_sotien_vat, int.Parse(vat.Text), d_sotien_vat, d_giaban, d_giamua, d_sl1, d_sl2, d_tyle, d_giabancu, d_giamuacu, d_vat_sotien);
                dtct.AcceptChanges(); dataGrid1.Refresh();
                s_tyle = tyle.Text;
                s_vat = vat.Text;
                emp_detail();
                vat.Text = s_vat;
                tyle.Text = s_tyle;
                tenthuoc.Focus();
                bSave = true;
            }
        }
        private bool kiemtra()
        {
            i_mabd = 0;
            if (mathuoc.Text == "" && tenthuoc.Text == "")
            {
                tenthuoc.Focus();
                return false;
            }
            if ((mathuoc.Text == "" && tenthuoc.Text != "") || (mathuoc.Text != "" && tenthuoc.Text == ""))
            {
                if (mathuoc.Text == "")
                {
                    MessageBox.Show("Nhập mã số !", DAL.AccessData.Msg);
                    mathuoc.Focus();
                    return false;
                }
                else if (tenthuoc.Text == "")
                {
                    MessageBox.Show("Nhập tên !", DAL.AccessData.Msg);
                    tenthuoc.Focus();
                    return false;
                }
            }
            DataRow r = m.getrowbyid(dtdmbd, "ma='" + mathuoc.Text + "'");
            if (r == null)
            {
                MessageBox.Show("Mã số không hợp lệ !", DAL.AccessData.Msg);
                tenthuoc.Focus();
                return false;
            }
            i_mabd = int.Parse(r["id"].ToString());
            if (soluong.Text == "" || soluong.Text == "0.00" || soluong.Text == "0")
            {
                MessageBox.Show("Nhập số lượng !", DAL.AccessData.Msg);
                soluong.Focus();
                return false;
            }
            return true;
        }
        private void butXoa_Click(object sender, EventArgs e)
        {
            if (mathuoc.Text == "" || tenthuoc.Text == "") return;
            i_mabd = m.get_iXuat(s_mmyy, int.Parse(kho.SelectedValue.ToString()), l_id, int.Parse(stt.Text));
            if (i_mabd != 0)
            {
                DataRow r = m.getrowbyid(dtdmbd, "id=" + i_mabd);
                if (r != null)
                {
                    MessageBox.Show(r["ten"].ToString().Trim() + " " + r["dang"].ToString().Trim() + "\nĐã xuất không cho phép hủy !", DAL.AccessData.Msg);
                    return;
                }
            }
            if (bEdit) m.updrec_nhapct(dtxoa, m.get_stt(dtxoa), i_mabd, mathuoc.Text, tenthuoc.Text, hoatchat.Text, dvt.Text, handung.Text, losx.Text, int.Parse(mancc.Text), d_soluong, d_dongia, d_sotien_vat, int.Parse(vat.Text), d_sotien_vat, d_giaban, d_giamua, d_sl1, d_sl2, d_tyle, d_giabancu, d_giamuacu, d_vat_sotien);
            m.delrec(dtct, "stt=" + int.Parse(stt.Text));
            dtct.AcceptChanges(); dataGrid1.Refresh();
            if (dtct.Rows.Count == 0) emp_detail();
            else ref_text();
            bSave = true;
        }
        private void butSua_Click(object sender, EventArgs e)
        {
            if (cboSophieu.Items.Count == 0) return;
            if (m.bKhoaso(s_mmyy))
            {
                MessageBox.Show("Số liệu tháng" + s_mmyy.Substring(0, 2) + " năm " + s_mmyy.Substring(2, 2) + "đã khóa !\nNếu cần thay đổi thì vào mục khai báo hệ thống!", DAL.AccessData.Msg);
                return;
            }
            if (m.get_data("select idduyet from " + user + ".d_xuatll where idduyet=" + l_id).Tables[0].Rows.Count > 0)
            {
                MessageBox.Show("Hoá đơn này đã được hoàn trả, không được sửa !", DAL.AccessData.Msg); return;
            }
            ena_object(true); ena_button(true);
            bNew = false; bEdit = true;
            manguon_old = int.Parse(nguon.SelectedValue.ToString());
            makho_old = int.Parse(kho.SelectedValue.ToString());
            if (dtdmbd.Rows.Count == 0) load_dm();
            foreach (DataRow r1 in dtct.Rows)
            {
                i_mabd = m.get_iXuat(s_mmyy, makho_old, l_id, int.Parse(r1["stt"].ToString()));
                if (i_mabd != 0)
                {
                    DataRow r = m.getrowbyid(dtdmbd, "id=" + i_mabd);
                    if (r != null)
                    {
                        kho.Enabled = false;
                        break;
                    }
                }
            }
            dtsave = dtct.Copy();
            dtxoa.Clear(); dtthem.Clear();
            hoadon.Focus();
            ref_text();
        }
        private void butBoqua_Click(object sender, EventArgs e)
        {
            try
            {
                l_id = long.Parse(cboSophieu.SelectedValue.ToString());
            }
            catch { l_id = 0; }
            load_head(); load_grid();
            ena_object(false);
            ena_button(false);
            bSave = false;
            ref_text();
            butMoi.Focus();
        }
        private void butHuy_Click(object sender, EventArgs e)
        {
            try
            {
                if (cboSophieu.Items.Count == 0) return;
                if (m.bKhoaso(s_mmyy))
                {
                    MessageBox.Show("Số liệu tháng" + s_mmyy.Substring(0, 2) + " năm "+ s_mmyy.Substring(2, 2) +"đã khóa !\nNếu cần thay đổi thì vào mục khai báo hệ thống!", DAL.AccessData.Msg);
                    return;
                }
                if (m.get_data("select idduyet from " + user + ".d_xuatll where idduyet=" + l_id).Tables[0].Rows.Count > 0)
                {
                    MessageBox.Show("Hoá đơn này đã được hoàn trả, không được huỷ !", DAL.AccessData.Msg); return;
                }
                if (dtdmbd.Rows.Count == 0) load_dm();
                foreach (DataRow r1 in dtct.Rows)
                {
                    i_mabd = m.get_iXuat(s_mmyy, int.Parse(kho.SelectedValue.ToString()), l_id, int.Parse(r1["stt"].ToString()));
                    if (i_mabd != 0)
                    {
                        DataRow r = m.getrowbyid(dtdmbd, "id=" + i_mabd);
                        if (r != null)
                        {
                            MessageBox.Show(r["ten"].ToString().Trim() + " " + r["dang"].ToString().Trim() + "\nĐã xuất không cho phép hủy !", DAL.AccessData.Msg);
                            return;
                        }
                    }
                }
                if (MessageBox.Show("Đồng ý hủy số phiếu này ?", DAL.AccessData.Msg, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    foreach (DataRow r1 in dtct.Rows)
                    {
                        m.upd_theodoisua(m.get_capid_theodoisua, sophieu.Text, l_id, int.Parse(r1["mabd"].ToString()), r1["ten"].ToString(), decimal.Parse(r1["soluong"].ToString()), i_userid, "NHATHUOC", "d_nhapct_" + s_mmyy, 0, 0, 1);
                        m.upd_tonkhoct_nhapct("delete", s_mmyy, ngayhd.Text, l_id, int.Parse(r1["stt"].ToString()), decimal.Parse(r1["soluong"].ToString()), decimal.Parse(r1["sotien"].ToString()), int.Parse(r1["vat"].ToString()), makho_old, manguon_old, int.Parse(r1["mabd"].ToString()), r1["handung"].ToString(), r1["losx"].ToString(), int.Parse(mancc.Text), "M", decimal.Parse(r1["giaban"].ToString()), decimal.Parse(r1["dongia"].ToString()), decimal.Parse(r1["sotienvat"].ToString()), (chietkhau.Text != "") ? decimal.Parse(chietkhau.Text) : 0);
                    }
                    m.execute_data("delete from " + user + ".d_nhapct_"+s_mmyy+" where id=" + l_id);
                    m.execute_data("delete from " + user + ".d_nhapll_"+s_mmyy+" where id=" + l_id);
                    m.delrec(dtll, "id=" + l_id);
                    cboSophieu.Refresh();
                    if (cboSophieu.Items.Count > 0) l_id = long.Parse(cboSophieu.SelectedValue.ToString());
                    else l_id = 0;
                    load_head(); load_grid(); ref_text();
                }
            }
            catch { }
        }
        private void butIn_Click(object sender, EventArgs e)
        {
            if (dtct.Rows.Count == 0) return;
            sql = "select a.stt,a.mabd,b.ma,trim(b.ten)||' '||b.hamluong as ten,nullif(b.tenhc,' ') as tenhc,b.dang,a.handung,a.losx,";
            sql += "a.soluong,a.dongia,a.vat,a.sotien,round(a.soluong*a.giamua,3) as tongtien,";
            sql += "a.giaban,a.giamua,c.ten as tenhang,d.ten as tennuoc,a.sl1,a.sl2,a.tyle,a.giabancu,a.giamuacu,a.tyle_ggia,a.st_ggia,a.soluong*a.giamua as sotienvat";
            sql += " from " + user + ".d_nhapct_"+s_mmyy+" a," + user + ".d_dmbd b," + user + ".d_dmhang c," + user + ".d_dmnuoc d where a.mabd=b.id and b.mahang=c.id and b.manuoc=d.id and a.id=" + l_id + " order by a.stt";
            DataTable dttmp = m.get_data(sql).Tables[0];
            DataRow r = m.getrowbyid(dtnx, "id=" + mancc.Text + "");
            string _dc = r["diachi"].ToString().Trim(), _maso = r["masothue"].ToString().Trim();
            if (r == null)
            {
                MessageBox.Show("Nhà cung cấp không hợp lệ !", DAL.AccessData.Msg);
                mancc.Focus();
                return;
            }
            frmReport f = new frmReport(m, dttmp, "", "d_phieunhap.rpt", cboSophieu.Text, ngaysp.Text, "", "", nguoigiao.Text, hoadon.Text, ngayhd.Text, tennhacc.Text, kho.Text.Trim(),"", _dc, _maso);
            //f.ShowDialog();
            this.FormMain.OpenTab("Phiếu Nhập", f);
        }
        private void butKetthuc_Click(object sender, EventArgs e)
        {
            //if (bSave)
            //{
            //    if (MessageBox.Show("Bạn có muốn lưu dữ liệu trước khi kết thúc không?", DAL.AccessData.Msg, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            //        butLuu_Click(null, null);
            //    else 
            //        this.Close();
            //}
            //this.Close();
        }
        private void tenthuoc_TextChanged(object sender, EventArgs e)
        {
            if (this.ActiveControl == tenthuoc)
            {
                Filter_dmbd(tenthuoc.Text);
                listDmbd.BrowseToDmbd(tenthuoc, mathuoc, sl1, mathuoc.Location.X, mathuoc.Location.Y + mathuoc.Height - 2, mathuoc.Width + label14.Width + tenthuoc.Width + label15.Width + hoatchat.Width + label16.Width + dvt.Width + 12, mathuoc.Height + 2);
            }
        }
        private void Filter_dmbd(string ten)
        {
            try
            {
                CurrencyManager cm = (CurrencyManager)BindingContext[listDmbd.DataSource];
                DataView dv = (DataView)cm.List;
                dv.RowFilter = "ten like '%" + ten.Trim() + "%'" + " or tenhc like '%" + ten.Trim() + "%'";
            }
            catch { }
        }
        private void tenthuoc_Validated(object sender, EventArgs e)
        {
            if (!listDmbd.Focused) listDmbd.Hide();
        }
        private void tenthuoc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up) listDmbd.Focus();
            else if (e.KeyCode == Keys.Enter)
            {
                if (listDmbd.Visible) listDmbd.Focus();
                else SendKeys.Send("{Tab}");
            }
        }
        private void mathuoc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up) listDmbd.Focus();
            else if (e.KeyCode == Keys.Enter)
            {
                if (listDmbd.Visible) listDmbd.Focus();
                else SendKeys.Send("{Tab}");
            }
        }
        private void mathuoc_TextChanged(object sender, EventArgs e)
        {
            if (this.ActiveControl == mathuoc)
            {
                Filter_dmbd(mathuoc.Text);
                listDmbd.BrowseToDmbd(mathuoc, tenthuoc, sl1, mathuoc.Location.X, mathuoc.Location.Y + mathuoc.Height - 2, mathuoc.Width + label14.Width + tenthuoc.Width + label15.Width + hoatchat.Width + label16.Width + dvt.Width + 12, mathuoc.Height + 2);
            }
        }
        private void mathuoc_Validated(object sender, EventArgs e)
        {
            if (mathuoc.Text != "")
            {
                DataRow r = m.getrowbyid(dtdmbd, "ma='" + mathuoc.Text + "'");
                if (r != null)
                {
                    tenthuoc.Text = r["ten"].ToString();
                    dvt.Text = r["dang"].ToString();
                    hoatchat.Text = r["tenhc"].ToString();
                    hang.Text = r["tenhang"].ToString();
                    nuocsx.Text = r["tennuoc"].ToString();
                    d_giaban = decimal.Parse(r["dongia"].ToString());
                    giamua_cu.Text = d_giaban.ToString("###,###,###,##0");
                    d_giaban = decimal.Parse(r["giaban"].ToString());
                    giaban_cu.Text = d_giaban.ToString("###,###,###,##0");
                    //string sotk = tkno.Text.Trim();
                    //if (sotk.IndexOf(r["sotk"].ToString()) == -1)
                    //{
                    //    sotk += (sotk != "") ? "," : "";
                    //    sotk += r["sotk"].ToString().Trim();
                    //    tkno.Text = sotk;
                    //}
                }
            }
            if (!listDmbd.Focused) listDmbd.Hide();
        }
        private void tennhacc_TextChanged(object sender, EventArgs e)
        {
            if (this.ActiveControl == tennhacc)
            {
                Filter_dmnx(tennhacc.Text);
                listDmnx.BrowseToDmnx(tennhacc, mancc, chietkhau);
                gThongtin.Height = 87 + listDmnx.Height - tennhacc.Height;
                gChitiet.SendToBack();
            }
        }
        private void Filter_dmnx(string ten)
        {
            try
            {
                CurrencyManager cm = (CurrencyManager)BindingContext[listDmnx.DataSource];
                DataView dv = (DataView)cm.List;
                dv.RowFilter = "ten like '%" + ten.Trim() + "%'";
            }
            catch { }
        }

        private void tennhacc_Validated(object sender, EventArgs e)
        {
            if (!listDmnx.Focused) listDmnx.Hide();
            if (tennhacc.Text != "" && mancc.Text == "")
            {
                DataRow r = m.getrowbyid(dtnx, "ten='" + tennhacc.Text + "'");
                if (r != null) mancc.Text = r["id"].ToString();
            }
        }

        private void tennhacc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up) listDmnx.Focus();
            else if (e.KeyCode == Keys.Enter)
            {
                if (listDmnx.Visible) listDmnx.Focus();
                else SendKeys.Send("{Tab}");
            }
        }

        private void mancc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) SendKeys.Send("{Tab}");
        }

        private void butLuu_Click(object sender, EventArgs e)
        {
            if (sophieu.Text.Trim() == "")
            {
                MessageBox.Show("Nhập số phiếu!"); sophieu.Focus(); return;
            }
            if (hoadon.Text.Trim() == "")
            {
                MessageBox.Show("Nhập số hoá đơn!"); hoadon.Focus(); return;
            }
            if (mancc.Text.Trim() == "")
            {
                MessageBox.Show("Nhập nhà cung cấp!"); mancc.Focus(); return;
            }
            if (mathuoc.Text != "" && tenthuoc.Text != "")
            {
                DataRow r = m.getrowbyid(dtdmbd, "ma='" + mathuoc.Text + "'");
                if (r == null)
                {
                    MessageBox.Show("Mã số không hợp lệ !", DAL.AccessData.Msg);
                    tenthuoc.Focus();
                    return;
                }
                i_mabd = int.Parse(r["id"].ToString());
                m.updrec_nhapct(dtct, m.get_stt(dtct), i_mabd, mathuoc.Text, tenthuoc.Text, hoatchat.Text, dvt.Text, handung.Text, losx.Text, int.Parse(mancc.Text), d_soluong, d_dongia, d_sotien_vat, int.Parse(vat.Text), d_sotien_vat, d_giaban, d_giamua, d_sl1, d_sl2, d_tyle, d_giabancu, d_giamuacu, d_vat_sotien);
                dtct.AcceptChanges(); dataGrid1.Refresh();
            }
            l_id = (bNew) ? m.get_capid : l_id;
            if (!m.upd_nhapll(s_mmyy, l_id, sophieu.Text, ngaysp.Text, hoadon.Text, ngayhd.Text, "M", nguoigiao.Text, int.Parse(mancc.Text), int.Parse(kho.SelectedValue.ToString()), int.Parse(nguon.SelectedValue.ToString()), tkno.Text, tkco.Text, i_userid, (chietkhau.Text != "") ? decimal.Parse(chietkhau.Text) : 0))
            {
                MessageBox.Show("Không cập nhật được thông tin phiếu nhập kho !", DAL.AccessData.Msg);
                return;
            }
            if (!bNew && bEdit)
            {
                foreach (DataRow r in dtct.Rows)
                {
                    DataRow nr = m.getrowbyid(dtsave, "mabd=" + int.Parse(r["mabd"].ToString()));
                    if (nr != null)
                    {
                        decimal d_soluong_old = decimal.Parse(nr["soluong"].ToString());
                        if (d_soluong_old != decimal.Parse(r["soluong"].ToString()))
                            m.upd_theodoisua(m.get_capid_theodoisua, sophieu.Text, l_id, int.Parse(r["mabd"].ToString()), r["ten"].ToString(), d_soluong_old, i_userid, "NT", "d_nhapct_" + s_mmyy, 0, 1, 0);
                    }
                }
                if (manguon_old != int.Parse(nguon.SelectedValue.ToString()) || makho_old != int.Parse(kho.SelectedValue.ToString()))
                {
                    foreach (DataRow r1 in dtsave.Rows)
                    {
                        m.execute_data("delete from " + user + ".d_nhapct_"+s_mmyy+" where id=" + l_id + " and stt=" + int.Parse(r1["stt"].ToString()));
                        m.upd_tonkhoct_nhapct("delete", s_mmyy, ngayhd.Text, l_id, int.Parse(r1["stt"].ToString()), decimal.Parse(r1["soluong"].ToString()), decimal.Parse(r1["sotien"].ToString()), int.Parse(r1["vat"].ToString()), makho_old, manguon_old, int.Parse(r1["mabd"].ToString()), r1["handung"].ToString(), r1["losx"].ToString(), int.Parse(mancc.Text), "M", decimal.Parse(r1["giaban"].ToString()), decimal.Parse(r1["dongia"].ToString()), decimal.Parse(r1["sotienvat"].ToString()), (chietkhau.Text != "") ? decimal.Parse(chietkhau.Text) : 0);
                    }
                    dtsave.Clear();
                }
                foreach (DataRow r1 in dtxoa.Rows)
                {
                    m.upd_theodoisua(m.get_capid_theodoisua, sophieu.Text, l_id, int.Parse(r1["mabd"].ToString()), r1["ten"].ToString(), decimal.Parse(r1["soluong"].ToString()), i_userid, "NT", "d_nhapct_" + s_mmyy, 0, 0, 1);
                    m.execute_data("delete from " + user + ".d_nhapct_" + s_mmyy + " where id=" + l_id + " and stt=" + long.Parse(r1["stt"].ToString()));
                }
                foreach (DataRow r in dtthem.Rows)
                    m.upd_theodoisua(m.get_capid_theodoisua, sophieu.Text, l_id, int.Parse(r["mabd"].ToString()), r["ten"].ToString(), decimal.Parse(r["soluong"].ToString()), i_userid, "NT", "d_nhapct_" + s_mmyy, 1, 0, 0);
                foreach (DataRow r1 in dtsave.Rows)
                    m.upd_tonkhoct_nhapct("delete", s_mmyy, ngayhd.Text, l_id, int.Parse(r1["stt"].ToString()), decimal.Parse(r1["soluong"].ToString()), decimal.Parse(r1["sotien"].ToString()), int.Parse(r1["vat"].ToString()), makho_old, manguon_old, int.Parse(r1["mabd"].ToString()), r1["handung"].ToString(), r1["losx"].ToString(), int.Parse(mancc.Text), "M", decimal.Parse(r1["giaban"].ToString()), decimal.Parse(r1["dongia"].ToString()), decimal.Parse(r1["sotienvat"].ToString()), (chietkhau.Text != "") ? decimal.Parse(chietkhau.Text) : 0);
            }
            foreach (DataRow r1 in dtct.Rows)
            {
                m.upd_nhapct(s_mmyy, l_id, int.Parse(r1["stt"].ToString()), int.Parse(r1["mabd"].ToString()),int.Parse(mancc.Text), r1["handung"].ToString(), r1["losx"].ToString(), int.Parse(r1["vat"].ToString()), decimal.Parse(r1["soluong"].ToString()), decimal.Parse(r1["dongia"].ToString()), decimal.Parse(r1["sotien"].ToString()), decimal.Parse(r1["giaban"].ToString()), decimal.Parse(r1["giamua"].ToString()), decimal.Parse(r1["sl1"].ToString()), decimal.Parse(r1["sl2"].ToString()), decimal.Parse(r1["tyle"].ToString()), decimal.Parse(r1["giabancu"].ToString()), decimal.Parse(r1["giamuacu"].ToString()), 0, 0);
                m.upd_tonkhoct_nhapct("insert", s_mmyy, ngayhd.Text, l_id, int.Parse(r1["stt"].ToString()), decimal.Parse(r1["soluong"].ToString()), decimal.Parse(r1["sotien"].ToString()), int.Parse(r1["vat"].ToString()), int.Parse(kho.SelectedValue.ToString()), int.Parse(nguon.SelectedValue.ToString()), int.Parse(r1["mabd"].ToString()), r1["handung"].ToString(), r1["losx"].ToString(), int.Parse(mancc.Text), "M", decimal.Parse(r1["giaban"].ToString()), decimal.Parse(r1["dongia"].ToString()), decimal.Parse(r1["sotienvat"].ToString()), (chietkhau.Text != "") ? decimal.Parse(chietkhau.Text) : 0);
            }
            m.updrec_nhapll(dtll, l_id, sophieu.Text, ngaysp.Text, hoadon.Text, ngayhd.Text, nguoigiao.Text, int.Parse(mancc.Text), int.Parse(kho.SelectedValue.ToString()), int.Parse(nguon.SelectedValue.ToString()), tkno.Text, tkco.Text, (chietkhau.Text != "") ? decimal.Parse(chietkhau.Text) : 0);
            try
            {
                if (dtll.Rows.Count > 0) cboSophieu.SelectedIndex = dtll.Rows.Count - 1;
            }
            catch { }
            ena_object(false);
            ena_button(false);
            bSave = false; bNew = false; bEdit = false;
            ref_text();
            butMoi.Focus();
        }

        private void bNut_SizeChanged(object sender, EventArgs e)
        {
            bNut.Location = new Point((this.Width - 628) / 2 + 1, (this.Height - 470) + 341);
        }

        private void sl1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SendKeys.Send("{Tab}");
            }
        }

        private void listDmbd_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                DataRow r = m.getrowbyid(dtdmbd, "ma='" + mathuoc.Text + "'");
                if (r != null)
                {
                    mathuoc.Text = r["ma"].ToString();
                    tenthuoc.Text = r["ten"].ToString();
                    dvt.Text = r["dang"].ToString();
                    hoatchat.Text = r["tenhc"].ToString();
                    hang.Text = r["tenhang"].ToString();
                    nuocsx.Text = r["tennuoc"].ToString();
                    d_giamuacu = decimal.Parse(r["dongia"].ToString());
                    giamua_cu.Text = d_giaban.ToString("###,###,###,##0.00");
                    d_giabancu = decimal.Parse(r["giaban"].ToString());
                    giaban_cu.Text = d_giaban.ToString("###,###,###,##0.00");
                    //string sotk = tkno.Text.Trim();
                    //if (sotk.IndexOf(r["sotk"].ToString()) == -1)
                    //{
                    //    sotk += (sotk != "") ? "," : "";
                    //    sotk += r["sotk"].ToString().Trim();
                    //    tkno.Text = sotk;
                    //}
                }
            }
        }

        private void listDmnx_Validated(object sender, EventArgs e)
        {
            gThongtin.Height = 87;
            gChitiet.BringToFront();
        }

        private void sophieu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SendKeys.Send("{Tab}{F4}");
            }
        }

        private void vat_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SendKeys.Send("{Tab}{Tab}");
            }
        }

        private void losx_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                butThem.Focus();
            }
        }

        private void kho_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                mathuoc.Focus();
            }
        }

        private void cboSophieu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                butMoi.Focus();
            }
        }

        private void sl2_Validated(object sender, EventArgs e)
        {
            try 
            {
                d_sl1 = decimal.Parse(sl1.Text);
                d_sl2 = decimal.Parse(sl2.Text);
                d_soluong = d_sl1 * d_sl2;
                soluong.Text = d_soluong.ToString("#,###.0");
                d_sotien_vat = d_soluong * d_dongia;
                if (vat.Text != "") i_vat = int.Parse(vat.Text);
                d_st_vat = (decimal.Parse(i_vat.ToString()) * d_sotien_vat) / 100;
                st_vat.Text = d_st_vat.ToString("###,###,##0.00");
                sotien_vat.Text = d_sotien_vat.ToString("###,###,##0.00");
                d_vat_sotien = d_sotien_vat + d_st_vat;
                vat_sotien.Text = d_vat_sotien.ToString("###,###,##0.00");
            }
            catch { d_soluong = 0; }
        }

        private void giamua_Validated(object sender, EventArgs e)
        {
            try
            {
                d_dongia = (giamua.Text == "") ? 0 : decimal.Parse(giamua.Text); ;
                giamua.Text = d_dongia.ToString("###,###,##0.00");
                d_sotien_vat=d_soluong * d_dongia;
                if (vat.Text != "") i_vat = int.Parse(vat.Text);
                d_st_vat = (decimal.Parse(i_vat.ToString()) * d_sotien_vat) / 100;
                d_giamua = d_dongia + d_dongia * i_vat / 100;
                d_giaban = d_giamua;
                giaban.Text = d_giaban.ToString("###,###,##0.00");
                sotien_vat.Text = d_sotien_vat.ToString("###,###,##0.00");
            }
            catch { d_dongia = 0; }
        }

        private void vat_Validated(object sender, EventArgs e)
        {
            try
            {
                i_vat = (vat.Text == "") ? 0 : int.Parse(vat.Text);
                vat.Text = i_vat.ToString();
                d_st_vat = (d_sotien_vat * decimal.Parse(i_vat.ToString())) / 100;
                st_vat.Text = d_st_vat.ToString("###,###,##0.00");
                d_giamua = d_dongia + d_dongia * i_vat / 100;
                d_giaban = d_giamua;
                giaban.Text = d_giaban.ToString("###,###,##0.00"); ;
                d_vat_sotien = d_sotien_vat + d_st_vat;
                vat_sotien.Text = d_vat_sotien.ToString("###,###,##0.00");
            }
            catch { }
        }

        private void tyle_Validated(object sender, EventArgs e)
        {
            try
            {
                d_tyle= (tyle.Text == "0") ? 0 : decimal.Parse(tyle.Text);
                d_giaban = d_giaban + (d_giaban * d_tyle / 100);
                giaban.Text = d_giaban.ToString("###,###,##0.00");
            }
            catch { }
        }

        private void giaban_Validated(object sender, EventArgs e)
        {
            try
            {
                d_giaban = decimal.Parse(giaban.Text);
                if (d_giaban < d_dongia)
                {
                    MessageBox.Show("Giá bán không được nhỏ hơn giá mua !", DAL.AccessData.Msg);
                    giaban.Focus();
                    return;
                }
                d_tyle = (d_giaban / d_giamua - 1) * 100;
                tyle.Text = d_tyle.ToString("#,##0.00");
            }
            catch { }
        }
        private void MaskDigit(KeyPressEventArgs e)
        {
            if (Char.IsDigit(e.KeyChar) || e.KeyChar == 8 || e.KeyChar == '.') e.Handled = false;
            else e.Handled = true;
        }
        private void MaskDigit_ngay(KeyPressEventArgs e)
        {
            if (Char.IsDigit(e.KeyChar) || e.KeyChar == '/') e.Handled = false;
            else e.Handled = true;
        }

        private void ngaysp_KeyPress(object sender, KeyPressEventArgs e)
        {
            MaskDigit_ngay(e);
        }

        private void sl1_KeyPress(object sender, KeyPressEventArgs e)
        {
            MaskDigit(e);
        }

        private void cboSophieu_SelectedIndexChanged(object sender, EventArgs e)
        {
            try 
            {
                l_id = long.Parse(cboSophieu.SelectedValue.ToString());
                load_head();
                load_grid();
                ref_text();
            }
            catch { l_id = 0; }
        }

        private void dataGrid1_CurrentCellChanged(object sender, EventArgs e)
        {
            try 
            {
                ref_text();
            }
            catch { }
        }

        private void sl1_Validated(object sender, EventArgs e)
        {
            try
            {
                d_sl1 = decimal.Parse(sl1.Text);
                d_sl2 = decimal.Parse(sl2.Text);
                d_soluong = d_sl1 * d_sl2;
                soluong.Text = d_soluong.ToString("#,###.0");
                d_sotien_vat = d_soluong * d_dongia;
                if (vat.Text != "") i_vat = int.Parse(vat.Text);
                d_st_vat = (decimal.Parse(i_vat.ToString()) * d_sotien_vat) / 100;
                st_vat.Text = d_st_vat.ToString("###,###,##0.00");
                sotien_vat.Text = d_sotien_vat.ToString("###,###,##0.00");
                d_vat_sotien = d_sotien_vat + d_st_vat;
                vat_sotien.Text = d_vat_sotien.ToString("###,###,##0.00");
            }
            catch { d_soluong = 0; }
        }

        private void ngaysp_Validated(object sender, EventArgs e)
        {
            if (!m.bNgay(ngaysp.Text.Trim()))
            {
                MessageBox.Show("Ngày không hợp lệ! Vui lòng nhập lại theo định dạng : dd/MM/yyyy", DAL.AccessData.Msg);
                ngaysp.Focus();
                return;
            }
        }

        private void ngayhd_Validated(object sender, EventArgs e)
        {
            if (!m.bNgay(ngayhd.Text.Trim()))
            {
                MessageBox.Show("Ngày không hợp lệ! Vui lòng nhập lại theo định dạng : dd/MM/yyyy", DAL.AccessData.Msg);
                ngayhd.Focus();
                return;
            }
        }
    }
}